package vn.com.bookstore.controller;

import java.util.HashMap;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import vn.com.bookstore.domain.model.Book;
import vn.com.bookstore.domain.model.BookType;
import vn.com.bookstore.service.BooksOnlineService;

@Controller
public class HomeController {

	private static final Logger logger = LoggerFactory
			.getLogger(HomeController.class);
	@Autowired
	private BooksOnlineService booksOnlineService;

	@RequestMapping(value = "/quan", method = RequestMethod.GET)
	public String openOffline(Model model) {
		return "redirect:/online/home";
	}

	@RequestMapping(value = "/online/home", method = RequestMethod.GET)
	public String openHomepage(Model model) {
		/*
		 * SecurityContext context = SecurityContextHolder.getContext(); String
		 * username = context.getAuthentication().getName(); Object user =
		 * context.getAuthentication().getPrincipal(); String role =
		 * StringUtils.EMPTY; if(user instanceof User){ User userDetail =
		 * (User)user; for (GrantedAuthority ga : userDetail.getAuthorities() )
		 * { //TODO save to list with account has many role access role =
		 * ga.getAuthority(); } } logger.info(role);
		 */
		logger.info("openHomePage()");
		List<BookType> bookTypes = booksOnlineService.getAllBookType();
		HashMap<Integer, List<Book>> mapBooks = new HashMap<Integer, List<Book>>();
		for (BookType bt : bookTypes) {
			mapBooks.put(bt.getId(),
					booksOnlineService.getListBooKByCategory(bt.getName()));
		}

		model.addAttribute("category", bookTypes);
		model.addAttribute("bookMap", mapBooks);

		return "website/home/home-page";
	}

	@RequestMapping(value = "/online/ajax/getBookCategory", method = RequestMethod.GET)
	public @ResponseBody
	ModelAndView getCategory() {
		ModelAndView model = new ModelAndView("website/book/category-list");
		List<BookType> lisBookTypes = booksOnlineService.getAllBookType();
		model.addObject("listCategory", lisBookTypes);
		return model;
	}

}
